package com.sunb2b.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.sunb2b.entity.Product;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Staticizer {
    private String tplDir;
    private Configuration cfg;
    
    public void process(Map env) throws IOException, TemplateException{
    	
    	Map data = (Map)env.get("data");
    	String tplName = (String)env.get("tpl");
    	String outputFileName = (String)env.get("outputFileName");
        Template tpl = cfg.getTemplate(tplName);
        
        File f = new File(outputFileName);
        if(!f.exists()){
            //f.createNewFile();
        	File p = f.getParentFile();
        	if(!p.exists()){
        		p.mkdirs();
        	}
        	//System.out.println("file not exist");
        }
        BufferedWriter out = new BufferedWriter(
        		new OutputStreamWriter(
        				new FileOutputStream(outputFileName), "utf-8"));
        tpl.process(data, out);
        out.close();
    }
    
    public Staticizer(String tplDir) throws IOException {
        this.tplDir = tplDir;
        this.cfg = new Configuration();
        this.cfg.setDirectoryForTemplateLoading(
            new File(tplDir)
        );
        this.cfg.setDefaultEncoding("utf-8");
        this.cfg.setObjectWrapper(new DefaultObjectWrapper());
    }
    
    public String getTplDir() {
        return tplDir;
    }
    public void setTplDir(String tplDir) {
        this.tplDir = tplDir;
    }
    
}
